package org.jeecg.hr.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.autopoi.poi.excel.ExcelImportUtil;
import org.jeecg.autopoi.poi.excel.def.NormalExcelConstants;
import org.jeecg.autopoi.poi.excel.entity.ExportParams;
import org.jeecg.autopoi.poi.excel.entity.ImportParams;
import org.jeecg.autopoi.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.hr.entity.SalaryTemplate;
import org.jeecg.hr.entity.SalaryTemplateDetail;
import org.jeecg.hr.service.SalaryTemplateDetailService;
import org.jeecg.hr.service.SalaryTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 薪酬方案
 * @Author: MxpIO
 */
@Api(tags = "薪酬方案")
@RestController
@RequestMapping("/hr/salary/template")
@Slf4j
public class SalaryTemplateController extends JeecgController<SalaryTemplate, SalaryTemplateService> {

	@Autowired
	private SalaryTemplateService salaryTemplateService;

	@Autowired
	private SalaryTemplateDetailService salaryTemplateDetailService;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * 
	 * @param salaryTemplate
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "薪酬方案-分页列表查询")
	@ApiOperation(value = "薪酬方案-分页列表查询", notes = "薪酬方案-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SalaryTemplate salaryTemplate,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		QueryWrapper<SalaryTemplate> queryWrapper = QueryGenerator.initQueryWrapper(salaryTemplate,
				req.getParameterMap());
		Page<SalaryTemplate> page = new Page<SalaryTemplate>(pageNo, pageSize);
		IPage<SalaryTemplate> pageList = salaryTemplateService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 * 
	 * @param salaryTemplate
	 * @return
	 */
	@AutoLog(value = "薪酬方案-添加")
	@ApiOperation(value = "薪酬方案-添加", notes = "薪酬方案-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SalaryTemplate salaryTemplate) {
		salaryTemplateService.save(salaryTemplate);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 * 
	 * @param salaryTemplate
	 * @return
	 */
	@AutoLog(value = "薪酬方案-编辑")
	@ApiOperation(value = "薪酬方案-编辑", notes = "薪酬方案-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SalaryTemplate salaryTemplate) {
		salaryTemplateService.updateById(salaryTemplate);
		return Result.OK("编辑成功!");
	}

	/**
	 * 添加
	 *
	 * @param salaryTemplate
	 * @return
	 */
	@AutoLog(value = "薪酬方案-添加(主从)")
	@ApiOperation(value = "薪酬方案-添加(主从)", notes = "薪酬方案-添加(主从)")
	@PostMapping(value = "/addWithChildren")
	public Result<?> addWithChildren(@RequestBody SalaryTemplate salaryTemplate) {
		salaryTemplateService.saveSalaryTemplateWithDetail(salaryTemplate);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param salaryTemplate
	 * @return
	 */
	@AutoLog(value = "薪酬方案-编辑(主从)")
	@ApiOperation(value = "薪酬方案-编辑(主从)", notes = "薪酬方案-编辑(主从)")
	@PutMapping(value = "/editWithChildren")
	public Result<?> editWithChildren(@RequestBody SalaryTemplate salaryTemplate) {
		SalaryTemplate salaryTemplateEntity = salaryTemplateService.getById(salaryTemplate.getId());
		if (salaryTemplateEntity == null) {
			return Result.error("未找到对应数据");
		}
		salaryTemplateService.updateSalaryTemplateWithDetail(salaryTemplate);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "薪酬方案-通过id删除")
	@ApiOperation(value = "薪酬方案-通过id删除", notes = "薪酬方案-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		salaryTemplateService.delSalaryTemplate(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "薪酬方案-批量删除")
	@ApiOperation(value = "薪酬方案-批量删除", notes = "薪酬方案-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		this.salaryTemplateService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, SalaryTemplate salaryTemplate) {
		return super.exportXls(request, salaryTemplate, SalaryTemplate.class, "薪酬方案");
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, SalaryTemplate.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/

	/*--------------------------------子表处理-薪酬方案明细-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * 
	 * @return
	 */
	@AutoLog(value = "薪酬方案明细-通过templateCode查询")
	@ApiOperation(value = "薪酬方案明细-通过templateCode查询", notes = "薪酬方案明细-通过templateCode查询")
	@GetMapping(value = "/listSalaryTemplateDetailByTemplateCode")
	public Result<?> listSalaryTemplateDetailByMainId(SalaryTemplateDetail salaryTemplateDetail,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

		Object tamplate = req.getParameter("templateCode");
		if(tamplate == null){
			return Result.OK();
		}
		QueryWrapper<SalaryTemplateDetail> queryWrapper = QueryGenerator.initQueryWrapper(salaryTemplateDetail,
				req.getParameterMap());
		Page<SalaryTemplateDetail> page = new Page<SalaryTemplateDetail>(pageNo, pageSize);
		IPage<SalaryTemplateDetail> pageList = salaryTemplateDetailService.page(page, queryWrapper);
		salaryTemplateDetailService.handleTransientVariable(pageList.getRecords());
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 * 
	 * @param salaryTemplateDetail
	 * @return
	 */
	@AutoLog(value = "薪酬方案明细-添加")
	@ApiOperation(value = "薪酬方案明细-添加", notes = "薪酬方案明细-添加")
	@PostMapping(value = "/addSalaryTemplateDetail")
	public Result<?> addSalaryTemplateDetail(@RequestBody SalaryTemplateDetail salaryTemplateDetail) {
		salaryTemplateDetailService.save(salaryTemplateDetail);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 * 
	 * @param salaryTemplateDetail
	 * @return
	 */
	@AutoLog(value = "薪酬方案明细-编辑")
	@ApiOperation(value = "薪酬方案明细-编辑", notes = "薪酬方案明细-编辑")
	@PutMapping(value = "/editSalaryTemplateDetail")
	public Result<?> editSalaryTemplateDetail(@RequestBody SalaryTemplateDetail salaryTemplateDetail) {
		salaryTemplateDetailService.updateById(salaryTemplateDetail);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "薪酬方案明细-通过id删除")
	@ApiOperation(value = "薪酬方案明细-通过id删除", notes = "薪酬方案明细-通过id删除")
	@DeleteMapping(value = "/deleteSalaryTemplateDetail")
	public Result<?> deleteSalaryTemplateDetail(@RequestParam(name = "id", required = true) String id) {
		salaryTemplateDetailService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "薪酬方案明细-批量删除")
	@ApiOperation(value = "薪酬方案明细-批量删除", notes = "薪酬方案明细-批量删除")
	@DeleteMapping(value = "/deleteBatchSalaryTemplateDetail")
	public Result<?> deleteBatchSalaryTemplateDetail(@RequestParam(name = "ids", required = true) String ids) {
		salaryTemplateDetailService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportSalaryTemplateDetail")
	public ModelAndView exportSalaryTemplateDetail(HttpServletRequest request,
			SalaryTemplateDetail salaryTemplateDetail) {
		// Step.1 组装查询条件
		QueryWrapper<SalaryTemplateDetail> queryWrapper = QueryGenerator.initQueryWrapper(salaryTemplateDetail,
				request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<SalaryTemplateDetail> pageList = salaryTemplateDetailService.list(queryWrapper);
		List<SalaryTemplateDetail> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId()))
					.collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "薪酬方案明细"); // 此处设置的filename无效
																// ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, SalaryTemplateDetail.class);
		mv.addObject(NormalExcelConstants.PARAMS,
				new ExportParams("薪酬方案明细报表", "导出人:" + sysUser.getRealname(), "薪酬方案明细"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importSalaryTemplateDetail/{templateCode}")
	public Result<?> importSalaryTemplateDetail(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("templateCode") String templateCode) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<SalaryTemplateDetail> list = ExcelImportUtil.importExcel(file.getInputStream(),
						SalaryTemplateDetail.class, params);
				for (SalaryTemplateDetail temp : list) {
					temp.setTemplateCode(templateCode);
				}
				long start = System.currentTimeMillis();
				salaryTemplateDetailService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-薪酬方案明细-end----------------------------------------------*/
}
